/**
 * 
 */
package id.ac.gunadarma.paracorp.services;

import id.ac.gunadarma.paracorp.model.EnglishSentence;
import id.ac.gunadarma.paracorp.model.TranslatedSentence;
import id.ac.gunadarma.paracorp.model.TranslationReference;
import id.ac.gunadarma.paracorp.repository.EnglishSentenceRepository;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author rezalesmana
 *
 */
@Service
@Transactional
public class EnglishSentenceService {
	
	@Autowired
	private EnglishSentenceRepository englishSentenceRepository;
	
	@Autowired
	private TranslatedSentenceService translatedSentenceService;
	
	public List<EnglishSentence> findAll(int pageIndex, int pageSize) {
		return getRepository().findAll(constructPageable(pageIndex, pageSize));
	}
	
	public List<EnglishSentence> findAll(int pageIndex, int pageSize, String language) {
		List<EnglishSentence> resultList = this.findAll(pageIndex, pageSize);
		
		for(EnglishSentence englishSentence : resultList) {
			TranslationReference reference = englishSentence.getTranslationReference(language);
			if(reference != null) {
				englishSentence.setTranslatedSentence(this.getTranslatedSentenceService().
						findById(reference.getTranslationReferenceId(), language));
			} else {
				englishSentence.setTranslatedSentence(new TranslatedSentence());
			}
		}
		
		return resultList;
	} 
	
	public EnglishSentence findBySentence(String sentence) {
		return getRepository().findBySentence(sentence);
	}
	
	public EnglishSentence save(EnglishSentence objectToSave) {
		return getRepository().save(objectToSave);
	}
	
	public List<EnglishSentence> save(List<EnglishSentence> objectToSaveList) {
		return getRepository().save(objectToSaveList);
	}
	
	public long getTotalSize() {
		return getRepository().getCount();
	}

	private Pageable constructPageable(int pageIndex, int pageSize) {
        Pageable pageable = new PageRequest(pageIndex, pageSize);
        return pageable;
    }
	
	private EnglishSentenceRepository getRepository() {
		return englishSentenceRepository;
	}
	
	private TranslatedSentenceService getTranslatedSentenceService() {
		return translatedSentenceService;
	}
	
}
